package com.synjones.zeuscloudweb.config;

import com.synjones.zeus.model.web.AdminBean;
import com.synjones.zeus.model.web.AdminRoleMenuBean;
import com.synjones.zeuscloudweb.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shany
 */
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    @Qualifier("loginServiceImpl")
    private LoginService loginService;
    /**
     * @author shany
     * 登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的token
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        String username = utoken.getUsername();
        AdminBean admin = loginService.findUserByName(username);
        //放入shiro.调用CredentialsMatcher检验密码
        return new SimpleAuthenticationInfo(admin, admin.getPassword(),this.getClass().getName());
    }
    /**
     * @author shany
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //获取session中的用户
        AdminBean admin =(AdminBean) principal.fromRealm(this.getClass().getName()).iterator().next();
        List<AdminRoleMenuBean>  adminRole = loginService.findAdminRoleMenuByUserId(String.valueOf(admin.getUserId()));
       List<String> permissions=new ArrayList<>();
        if(adminRole.size()>0) {
            for(AdminRoleMenuBean adminRoleMenuBean : adminRole) {
                if(adminRoleMenuBean.getMenuname()!=null) {
                        permissions.add(adminRoleMenuBean.getMenuname());
                    }
                }
            }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //将权限放入shiro中.
        info.addStringPermissions(permissions);
        return info;
    }

}
